<template>
  <div class="library-container">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索图书..."
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
      <div class="filter-buttons">
        <el-button
          v-for="category in categories"
          :key="category.id"
          :type="selectedCategory === category.id ? 'primary' : 'default'"
          @click="selectCategory(category.id)"
          size="small"
        >
          {{ category.name }}
        </el-button>
        <el-button
          type="text"
          size="small"
          @click="viewAllCategories"
          style="margin-left: 12px;"
        >
          查看全部分类 →
        </el-button>
      </div>
    </div>

    <!-- 图书列表 -->
    <div class="book-grid">
      <div 
        v-for="book in books"
        :key="book.id"
        class="book-card"
        @click="goToBookDetail(book.id)"
      >
        <div class="book-cover">
          <el-image
            :src="book.coverImage || '/default-book.jpg'"
            fit="cover"
            class="cover-image"
          />
          <div class="book-status">
            <el-tag 
              :type="book.status === 'AVAILABLE' ? 'success' : 'danger'"
              size="small"
            >
              {{ book.status === 'AVAILABLE' ? '可借阅' : '已借出' }}
            </el-tag>
          </div>
        </div>
        <div class="book-info">
          <h3 class="book-title">{{ book.title }}</h3>
          <p class="book-author">作者：{{ book.author }}</p>
          <p class="book-publisher">出版社：{{ book.publisher }}</p>
          <div class="book-meta">
            <span class="book-category">{{ book.categoryName }}</span>
            <span class="book-rating">
              <el-rate
                v-model="book.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                size="small"
              />
            </span>
          </div>
          <div class="book-actions">
            <el-button 
              type="primary" 
              size="small" 
              :disabled="book.status !== 'AVAILABLE'"
              @click.stop="borrowBook(book)"
            >
              {{ book.status === 'AVAILABLE' ? '借阅' : '已借出' }}
            </el-button>
            <el-button 
              type="default" 
              size="small" 
              icon="Star"
              @click.stop="toggleFavorite(book)"
            >
              {{ book.isFavorite ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button @click="loadMore" :loading="loading">加载更多</el-button>
    </div>

    <!-- 我的借阅记录 -->
    <div class="my-borrowing">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>我的借阅记录</span>
            <el-button type="text" @click="showAllBorrowings">查看全部</el-button>
          </div>
        </template>
        <div class="borrowing-list">
          <div 
            v-for="record in borrowingRecords"
            :key="record.id"
            class="borrowing-item"
          >
            <el-image
              :src="record.book.coverImage || '/default-book.jpg'"
              fit="cover"
              class="borrowing-cover"
            />
            <div class="borrowing-info">
              <h4>{{ record.book.title }}</h4>
              <p>借阅时间：{{ parseTime(record.borrowTime) }}</p>
              <p>应还时间：{{ parseTime(record.dueTime) }}</p>
              <div class="borrowing-status">
                <el-tag 
                  :type="getStatusType(record.status)"
                  size="small"
                >
                  {{ getStatusText(record.status) }}
                </el-tag>
                <el-button 
                  v-if="record.status === 'BORROWED'"
                  type="primary" 
                  size="small"
                  @click="returnBook(record)"
                >
                  归还
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getBookList, 
  getBookCategories, 
  searchBooks,
  borrowBook as apiBorrowBook,
  returnBook as apiReturnBook,
  favoriteBook,
  unfavoriteBook,
  getMyBorrowingRecords
} from '@/api/library'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref(null)
const categories = ref([{ id: null, name: '全部' }])
const books = ref([])
const borrowingRecords = ref([])
const loading = ref(false)
const hasMore = ref(true)

// 分页参数
const pagination = reactive({
  page: 1,
  size: 20
})

// 获取图书分类
const getCategories = async () => {
  try {
    const response = await getBookCategories()
    if (response.code === 200) {
      categories.value = [{ id: null, name: '全部' }, ...response.data]
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取图书列表
const getBooks = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page: reset ? 1 : pagination.page,
      size: pagination.size,
      categoryId: selectedCategory.value
    }
    
    const response = await getBookList(params)
    if (response.code === 200) {
      const newBooks = response.data.records || []
      if (reset) {
        books.value = newBooks
        pagination.page = 1
      } else {
        books.value.push(...newBooks)
      }
      
      hasMore.value = newBooks.length === pagination.size
      if (!reset) {
        pagination.page++
      }
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索图书
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    getBooks(true)
    return
  }
  
  loading.value = true
  try {
    const response = await searchBooks(searchKeyword.value, {
      page: 1,
      size: pagination.size
    })
    if (response.code === 200) {
      books.value = response.data.records || []
      hasMore.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  searchKeyword.value = ''
  getBooks(true)
}

// 加载更多
const loadMore = () => {
  getBooks()
}

// 借阅图书
const borrowBook = async (book) => {
  try {
    await ElMessageBox.confirm(`确认要借阅《${book.title}》吗？`, '确认借阅', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await apiBorrowBook(book.id)
    ElMessage.success('借阅成功')
    book.status = 'BORROWED'
    loadBorrowingRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('借阅失败:', error)
      ElMessage.error('借阅失败')
    }
  }
}

// 归还图书
const returnBook = async (record) => {
  try {
    await ElMessageBox.confirm(`确认要归还《${record.book.title}》吗？`, '确认归还', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await apiReturnBook(record.id)
    ElMessage.success('归还成功')
    record.status = 'RETURNED'
    loadBorrowingRecords()
    getBooks(true) // 刷新图书列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('归还失败:', error)
      ElMessage.error('归还失败')
    }
  }
}

// 切换收藏
const toggleFavorite = async (book) => {
  try {
    if (book.isFavorite) {
      await unfavoriteBook(book.id)
      book.isFavorite = false
      ElMessage.success('已取消收藏')
    } else {
      await favoriteBook(book.id)
      book.isFavorite = true
      ElMessage.success('已添加收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 获取借阅记录
const loadBorrowingRecords = async () => {
  try {
    const response = await getMyBorrowingRecords({ page: 1, size: 5 })
    if (response.code === 200) {
      borrowingRecords.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取借阅记录失败:', error)
  }
}

// 跳转到图书详情
const goToBookDetail = (bookId) => {
  router.push(`/library/book/${bookId}`)
}

// 查看全部借阅记录
const showAllBorrowings = () => {
  router.push('/library/borrowings')
}

// 查看全部分类
const viewAllCategories = () => {
  router.push('/library/categories')
}

// 工具函数
const getStatusType = (status) => {
  const typeMap = {
    'BORROWED': 'warning',
    'RETURNED': 'success',
    'OVERDUE': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'BORROWED': '借阅中',
    'RETURNED': '已归还',
    'OVERDUE': '已逾期'
  }
  return textMap[status] || status
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString()
}

// 页面加载
onMounted(() => {
  getCategories()
  getBooks(true)
  loadBorrowingRecords()
})
</script>

<style lang="scss" scoped>
.library-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 16px;
}

.search-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  
  .search-box {
    margin-bottom: 16px;
    
    .search-input {
      max-width: 400px;
    }
  }
  
  .filter-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
}

.book-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.book-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  }
  
  .book-cover {
    position: relative;
    height: 200px;
    
    .cover-image {
      width: 100%;
      height: 100%;
    }
    
    .book-status {
      position: absolute;
      top: 8px;
      right: 8px;
    }
  }
  
  .book-info {
    padding: 16px;
    
    .book-title {
      font-size: 16px;
      font-weight: 600;
      margin: 0 0 8px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .book-author, .book-publisher {
      color: #666;
      font-size: 14px;
      margin: 4px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .book-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 12px 0;
      
      .book-category {
        background: #f0f0f0;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
        color: #666;
      }
    }
    
    .book-actions {
      display: flex;
      gap: 8px;
      margin-top: 12px;
    }
  }
}

.load-more {
  text-align: center;
  margin: 20px 0;
}

.my-borrowing {
  margin-top: 40px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .borrowing-list {
    .borrowing-item {
      display: flex;
      gap: 12px;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .borrowing-cover {
        width: 60px;
        height: 80px;
        border-radius: 4px;
      }
      
      .borrowing-info {
        flex: 1;
        
        h4 {
          margin: 0 0 8px 0;
          font-size: 14px;
        }
        
        p {
          margin: 4px 0;
          font-size: 12px;
          color: #666;
        }
        
        .borrowing-status {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 8px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .library-container {
    padding: 8px;
  }
  
  .book-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
  }
  
  .search-header {
    padding: 16px;
  }
}
</style>
